package com.zhuoli.service.redis.client.template.redis;

import com.zhuoli.service.redis.client.action.GedisAction;
import com.zhuoli.service.redis.client.template.GedisTemplate;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Slf4j
public class RedisTemplate implements GedisTemplate {

    private JedisPool jedisPool;

    public RedisTemplate(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    public <T> T execute(GedisAction<T> action) {
        T result = null;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            result = action.doAction(jedis);
        } catch (Exception e) {
            log.error("Call redis failed.", e);
        } finally {
            assert jedis != null;
            jedis.close();
        }
        return result;
    }
}
